import { request } from '@/utils/request'

export type EntityType = 'task' | 'requirement' | 'defect' | 'document'

export interface Comment {
  id: string
  content: string
  author_id: string
  author_name?: string
  parent_comment_id?: string | null
  is_deleted?: boolean
  created_at: string
  updated_at?: string
}

export interface CommentCreate {
  content: string
  parent_comment_id?: string | null
}

export interface CommentUpdate {
  content?: string
  is_deleted?: boolean
}

export interface CommentListResponse {
  items: Comment[]
  total: number
  page: number
  page_size: number
}

// 获取评论列表
export const getComments = async (
  entityType: EntityType,
  entityId: string,
  page: number = 1,
  pageSize: number = 20
): Promise<CommentListResponse> => {
  const response = await request.get(`/${entityType}/${entityId}/comments`, {
    params: { page, page_size: pageSize }
  })
  
  if (response.data && response.data.success && response.data.data) {
    return response.data.data
  }
  
  return {
    items: [],
    total: 0,
    page,
    page_size: pageSize
  }
}

// 添加评论
export const addComment = async (
  entityType: EntityType,
  entityId: string,
  comment: CommentCreate
): Promise<{ id: string }> => {
  const response = await request.post(`/${entityType}/${entityId}/comments`, comment)
  
  if (response.data && response.data.success) {
    return response.data.data || { id: '' }
  }
  
  throw new Error(response.data?.message || '添加评论失败')
}

// 更新评论
export const updateComment = async (
  entityType: EntityType,
  entityId: string,
  commentId: string,
  comment: CommentUpdate
): Promise<void> => {
  const response = await request.put(`/${entityType}/${entityId}/comments/${commentId}`, comment)
  
  if (response.data && response.data.success === false) {
    throw new Error(response.data.message || '更新评论失败')
  }
}

// 删除评论（软删除/撤回）
export const deleteComment = async (
  entityType: EntityType,
  entityId: string,
  commentId: string
): Promise<void> => {
  const response = await request.delete(`/${entityType}/${entityId}/comments/${commentId}`)
  
  if (response.data && response.data.success === false) {
    throw new Error(response.data.message || '撤回评论失败')
  }
}

